<template>
  <Dialog v-model="dialogVisible" title="导入群号" width="600px">
    <el-form ref="formRef" :model="formData" label-width="100px" :rules="formRules">
      <el-form-item label="群号池" prop="poolName">
        <el-input v-model="formData.poolName" disabled />
      </el-form-item>
      <el-form-item label="文件上传" prop="file">
        <el-upload
          ref="uploadRef"
          class="upload-demo"
          drag
          action="#"
          :auto-upload="false"
          :limit="1"
          :on-change="handleFileChange"
          :on-exceed="handleExceed"
          :before-remove="handleRemove"
        >
          <Icon icon="ep:upload-filled" class="el-icon--upload" />
          <div class="el-upload__text">
            拖拽文件到此处或 <em>点击上传</em>
          </div>
          <template #tip>
            <div class="el-upload__tip">
              <p>文件格式要求：纯文本，每行一个群号</p>
              <p>文件大小限制：最大50MB</p>
            </div>
          </template>
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="flex justify-end">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleImport" :loading="importing">确定</el-button>
      </div>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { ImportTaskApi, ImportTaskType } from '@/api/yunkong/importtask'

defineOptions({ name: 'ImportDialog' })

const message = useMessage() // 消息弹窗
const dialogVisible = ref(false)
const importing = ref(false)
const formRef = ref()
const uploadRef = ref()

// 表单数据
const formData = reactive({
  poolId: undefined as number | undefined,
  poolName: '',
  file: null as File | null
})

// 表单校验规则
const formRules = reactive({
  file: [{ required: true, message: '请上传文件', trigger: 'change' }]
})

// 文件变更处理
const handleFileChange = (file: any) => {
  // 检查文件类型
  const isTextFile = file.raw.type === 'text/plain' || file.name.endsWith('.txt')
  if (!isTextFile) {
    message.error('请上传文本文件（.txt）')
    uploadRef.value.clearFiles()
    return false
  }
  
  // 检查文件大小（最大50MB）
  const isLt50M = file.size / 1024 / 1024 < 50
  if (!isLt50M) {
    message.error('文件大小不能超过50MB')
    uploadRef.value.clearFiles()
    return false
  }
  
  formData.file = file.raw
  return true
}

// 文件超出数量限制
const handleExceed = () => {
  message.error('只能上传一个文件')
}

// 移除文件
const handleRemove = () => {
  formData.file = null
  return true
}

// 导入处理
const handleImport = async () => {
  // 表单验证
  try {
    await formRef.value.validate()
  } catch (error) {
    return
  }
  
  if (!formData.file) {
    message.error('请选择要上传的文件')
    return
  }
  
  importing.value = true
  try {
    // 1. 创建导入任务
    const taskParams = {
      type: ImportTaskType.GROUP_NUMBER,
      businessId: formData.poolId as number,
      taskName: `导入群号到${formData.poolName}`,
      fileName: formData.file.name,
      fileSize: formData.file.size,
      params: JSON.stringify({ poolId: formData.poolId })
    }
    
    const taskId = await ImportTaskApi.createImportTask(taskParams)
    // taskId 判断
    if (!taskId) {
      message.error( '创建导入任务失败')
      return
    }
    
    
    // 2. 上传文件
    const uploadRes = await ImportTaskApi.uploadFile(taskId, formData.file)
    if (!uploadRes) {
      message.error('上传文件失败')
      return
    }
    
    message.success('文件上传成功，正在处理中')
    dialogVisible.value = false
    
    // 触发导入成功事件
    emit('success', taskId)
  } catch (error) {
    console.error('导入失败', error)
    message.error('导入失败，请重试')
  } finally {
    importing.value = false
  }
}

// 打开弹窗
const open = (poolId: number, poolName: string) => {
  dialogVisible.value = true
  formData.poolId = poolId
  formData.poolName = poolName
  formData.file = null
  
  // 清空上传列表
  if (uploadRef.value) {
    uploadRef.value.clearFiles()
  }
}

// 定义事件
const emit = defineEmits(['success'])

// 对外暴露方法
defineExpose({
  open
})
</script>

<style scoped>
.upload-demo {
  width: 100%;
}
.el-upload__tip {
  line-height: 1.2;
  margin-top: 10px;
}
</style> 